package com.itheima.interceptor;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.itheima.common.TokenHolder;
import com.itheima.util.JwtUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/*
 *
 * @Author longbosheng
 * @Date 2022/6/11 16:05
 * @PackageName:com.itheima.controller.interceptor
 * @ClassName: interceptor
 * @Description: TODO
 * @Version 1.0
 */
@Log4j2
@Component
public class UserInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("UTF-8");
        //获取 header里的token
        String token = request.getHeader("AuthorizationUser");
        System.out.println("拦截器token:" + token);
        //如果id有内容，证明可以登录
        if (StringUtils.isBlank(token)) {
            log.warn("token没有内容！拦截");
            return false;
        }
        //从token中解析出用户id
        DecodedJWT verify = JwtUtil.verify(token);
        if (verify==null){
            log.warn("token失效！拦截");
            return false;
        }
        String uid = verify.getClaim("id").asString();
        if (uid==null){
            log.warn("id没有内容！拦截");
        }
        //获取到的放入线程中
        TokenHolder.setCurrentId(uid);
        //放行
        log.info("放行");
        return true;
    }

    //    结束后清除threadLocal
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        TokenHolder.removeCurrentId();
    }
}
